const { list } = require('./mock')
const bodyParser = require('body-parser')
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();

const OSS = require('ali-oss')
const path = require("path")

const client = new OSS({
	// yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
	region: 'oss-cn-shanghai',
	// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
	accessKeyId: 'LTAI5t8ELnFwejupNYwECHFc',
	accessKeySecret: 'y82RU6Y7hnj1UkZGrAkqLHRqZQvmfQ',
	// 填写Bucket名称。
	bucket: '2007a-1',
});

const userList = [{
	avator: 'https://robohash.org/1231',
	nickname: '管理员',
	hot: 1,
	quanzi: 2,
	about: 3,
	aboutd: 4,
	username: 'admin',
	password: 'admin',
}, {
	avator: 'https://robohash.org/564564',
	nickname: '测试',
	hot: 11,
	quanzi: 22,
	about: 33,
	aboutd: 44,
	username: 'test',
	password: 'test',
}]

module.exports = app => {
	app.use(bodyParser.json())

	app.get('/api/list', (req, res) => {
		res.send({
			code: 200,
			data: list,
			message: 'ok'
		})
	})
	app.post('/api/list', (req, res) => {
		const { avator, nickname, createTime, content, images } = req.body;
		const data = {
			avator, nickname, createTime, content, images,
			id: Math.random().toString().slice(2)
		}

		list.unshift(data)

		res.send({
			code: 200,
			data,
			message: 'ok'
		})
	})

	app.post('/api/upload/image', multipartMiddleware, async (req, res) => {
		console.log(req.files)
		const result = await client.put(req.files.chunk.name, req.files.chunk.path);
		res.send({
			data: result,
			code: 200,
			message: 'OK'
		})
	})

	app.post('/api/login', (req, res) => {
		const { username, password } = req.body;

		const user = userList.find(v => v.username === username && v.password === password)

		if (user) {
			res.send({
				code: 200,
				message: 'ok',
				data: {
					userInfo: {
						...user,
						token: 'efnwkdwdw'
					}
				}
			})
		} else {
			res.send({
				code: 403,
				message: 'fail',
				data: null
			})
		}
	})
}